package cn.happy.favdish.view.fragments

import android.app.Dialog
import android.icu.lang.UCharacter.GraphemeClusterBreak.L
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import cn.happy.favdish.R
import cn.happy.favdish.databinding.FragmentRandomDishBinding
import cn.happy.favdish.model.entities.RandomDish
import cn.happy.favdish.view.viewmodel.RandomDishViewModel

class RandomDishFragment : Fragment() {

    private var _binding: FragmentRandomDishBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private lateinit var mRandomDishViewModel: RandomDishViewModel

    private var mProgressDialog: Dialog? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentRandomDishBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mRandomDishViewModel = ViewModelProvider(this)[RandomDishViewModel::class.java]

        mRandomDishViewModel.getRandomRecipeFromAPI()

        randomDishViewModelObserver()

    }

    /**
     * 获取数据
     */
    private fun randomDishViewModelObserver(){
        mRandomDishViewModel.loadRandomDish.observe(viewLifecycleOwner
        ) { loadRandomDish ->
            loadRandomDish?.let {
                if (it) {
                    showCustomProgressDialog()
                } else {
                    hideProgressDialog()
                }
            }
        }
        mRandomDishViewModel.randomDishResponse.observe(viewLifecycleOwner
        ) { randomDishResponse ->
            randomDishResponse?.let {
                // 接口返回的数据
                Log.e("reponse", it.toString())
            }
        }

        mRandomDishViewModel.randomDishLoadingError.observe(viewLifecycleOwner) {
            if (it) {

            }
        }
    }

    /**
     * 数据适配到页面
     */
    private fun setRandomDishResponseInUI(recipe:RandomDish){

    }

    private fun showCustomProgressDialog(){
        mProgressDialog = Dialog(requireActivity())
        mProgressDialog?.let{
            it.setContentView(R.layout.dialog_custom_progress)
            it.show()
        }
    }

    private fun hideProgressDialog(){
        mProgressDialog?.dismiss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}